package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findWithMaxScore(Long userId) {
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            query = new Query().with(Sort.by(Sort.Order.desc("score"))).limit(1);
            recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        }
        return recommendUser;
    }

    @Override
    public List<RecommendUser> queryRecommendUserList(Long userId) {
        return mongoTemplate.find(Query.query(Criteria.where("toUserId").is(userId)), RecommendUser.class);
    }

    @Override
    public RecommendUser queryByUserId(Long id, Long userId) {
        Query query = Query.query(Criteria
                .where("userId").is(id).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(id);
            recommendUser.setToUserId(userId);
            recommendUser.setScore(90d);
        }
        return recommendUser;
    }

    @Override
    public List<RecommendUser> queryCardsUserList(Long userId, int count) {
        List<UserLike> userLikes = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), UserLike.class);
        List<Long> likes = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        Criteria criteria = Criteria.where("toUserId").in(userId).and("userId").nin(likes);
        TypedAggregation<RecommendUser> aggregation = Aggregation.newAggregation(
                RecommendUser.class,
                Aggregation.match(criteria),
                Aggregation.sample(count)
        );
        AggregationResults<RecommendUser> result = mongoTemplate.aggregate(aggregation, RecommendUser.class);
        return result.getMappedResults();
    }
}
